/**
 * 1658. 将 x 减到 0 的最小操作数
 * https://leetcode.cn/problems/minimum-operations-to-reduce-x-to-zero/description/
 */
class Solution {
    public int minOperations(int[] nums, int x) {
        int sum = 0, n = nums.length;
        for(int a : nums) sum += a;
        int target = sum - x;

        if(target < 0) return -1;

        int ret = -1;
        for(int left = 0, right = 0, tmp = 0; right < n; right++) {
            // 1、进窗口
            tmp += nums[right];
            // 2、判断
            while(tmp > target) {
                // 3、出窗口
                tmp -= nums[left++];
            }
            // 4、更新结果
            if(tmp == target) ret = Math.max(ret, right - left + 1);
        }

        return ret == -1 ? -1 : n - ret;
    }
}